<template>
  <div class="wrapper" v-if="isDialogReadonly">
    <div class="context">
      <header>
        <div class="header-title">
          {{ route.query.id ? '编辑' : '添加' }}标签
        </div>
        <div class="close-icon" @click="() => setShowDialog(false)">×</div>
      </header>
      <el-alert
        title="【一键生成】客户端新建书签时候可用。输入链接即可，名称和封面自动生成！"
        type="info"
        :closable="false"
        v-if="isOffLine()"
      >
      </el-alert>
      <main v-loading="dialogLodingRef">
        <div
          :class="`mian-item ${formVerifyClassName.urlError}`"
          :style="{
            gridTemplateColumns:
            isOffLine() && !route.query.id ? '38px 1fr 90px' : '38px 1fr',
          }"
        >
          <label>网址</label>
          <div class="input">
            <input
              type="text"
              placeholder="请输入网址"
              v-model="formReactive.urlValue"
            />
          </div>
          <el-button
            v-if="isOffLine() && !route.query.id"
            style="background-color: var(--system-primary-color); border: none"
            type="primary"
            :loading="loadingRef"
            round
            class="btn"
            @click="!loadingRef && handleFastOk()"
            >一键生成</el-button
          >
        </div>
        <div :class="`mian-item ${formVerifyClassName.nameError}`">
          <label> 名称 </label>
          <div class="input">
            <input type="text" placeholder="请输入网址名称" v-model="formReactive.nameValue" />
          </div>
        </div>
        <div :class="`mian-item ${formVerifyClassName.srcError}`" style="margin-bottom: 50px">
          <label> 封面 </label>
          <CustomUpload v-model:src="formReactive.srcValue"/>
        </div>
      </main>
      <footer>
        <el-button
          type="info"
          round
          class="btn cancel"
          @click="() => setShowDialog(false)"
          >取消</el-button
        >
        <el-button
          type="primary"
          :loading="loadingRef"
          round
          class="btn ok"
          @click="!loadingRef && handleOk()"
          >确认</el-button
        >
      </footer>
    </div>
  </div>
</template>
<script setup name="MyDialog">
import { inject, ref, reactive ,  watch } from 'vue';
import { useRoute } from 'vue-router';
import Message from '../../components/Message/index.js';
import CustomUpload from '../../components/CustomUpload/index.vue';
import useSymbols from '../../compostions/useSymbols';
import { isOffLine } from '../../util/isOffLine';

const route = useRoute();

const {
  getList,
  addItem,
  isDialogReadonly,
  setShowDialog,
  getInfoById,
  updateInfoItem,
} = inject(useSymbols);


const dialogLodingRef = ref(false);
const loadingRef = ref(false);


const formReactive=reactive({
  urlValue: 'https://www.baidu.com',
  nameValue: '',
  srcValue:'',
})

// 校验时候-验证未通过时候的类名
const formVerifyClassName = reactive({
  urlError:'',
  nameError:'',
  srcError:'',
});

// 校验输入框必填
const verifyFormItem= ()=>{
  return new Promise((resolve, reject) => {
    Object.entries(formVerifyClassName).forEach(([k, v]) => formVerifyClassName[k] = '');
    const formDubArr = Object.entries(formReactive);
    let bool = true;
    for (let i = 0; i < formDubArr.length; i++){
      const [k, v] = formDubArr[i];
      switch (k) {
        case 'urlValue':
          if (!v) {
            formVerifyClassName.urlError = 'url-item-error';
            bool = false;
          }
          break;
        case 'nameValue':
          if (!v) {
            formVerifyClassName.nameError = 'name-item-error';
            bool = false;
        }
          break;
        case 'srcValue':
        if (!v){
          formVerifyClassName.srcError = 'src-item-error';
          bool = false;
        }
          break;
      }
    }
    resolve(bool)
  })
}
// 保存
const handleOk = async () => {
  const verifyFormRes =await verifyFormItem();
  if (!verifyFormRes) {
    throw new Error('校验不通过！！！！')
  };
  loadingRef.value = true;
  try {
    const res = {
      title: formReactive.nameValue,
      titleEn: '',
      screenshot: formReactive.srcValue,
      url: formReactive.urlValue,
    };
    if (route.query.id) {
      await updateInfoItem({ ...res, id: route.query.id });
    } else {
      await addItem(res);
    }
    setShowDialog(false);
    Message({ text: '保存成功!', type: 'success' });
    getList();
  } catch (err) {
    console.log(err);
    Message({ text: '保存失败!', type: 'error' });
  } finally {
    loadingRef.value = false;
  }
};

// 快速生成书签(客户端情况下可以使用)
const handleFastOk = async () => {
  try {
    loadingRef.value = true;
    const res = await window.myApi.sendUrl(formReactive.urlValue);
    await addItem(res);
    setShowDialog(false);
    Message({ text: '保存成功!', type: 'success' });
    getList();
  } catch (error) {
    Message({ text: '保存失败!', type: 'error' });
  } finally {
    loadingRef.value = false;
  }
};

// 编辑-获取详情
const getInfoDataById = async (id) => {
  dialogLodingRef.value = true;
  try {
    const res = await getInfoById(id);
    formReactive.urlValue = res.url;
    formReactive.nameValue = res.title;
    formReactive.srcValue = res.screenshot;
  } catch (error) {
    console.log(error);
  } finally {
    dialogLodingRef.value = false;
  }
};

watch(isDialogReadonly, (newShow) => {
  const MARK_ID = 'markId';
  if (newShow) {
    if (route.query.id) getInfoDataById(route.query.id);
  } else {
    formReactive.nameValue = '';
    formReactive.srcValue = '';
  }
  loadingRef.value = false;
});
</script>
<style scoped lang="less">
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.2);

  .context {
    position: relative;
    width: 480px;
    min-height: 200px;
    max-height: auto;
    background-color: #ffffff;
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 0 6px #999;

    header {
      position: relative;
      background-color: var(--system-primary-color);
      width: 100%;
      height: 40px;
      box-shadow: 0 0 1px #999999;
      padding: 0 14px;
      box-sizing: border-box;

      .header-title {
        color: #fff;
        font-size: 14px;
        font-weight: bold;
        line-height: 40px;
        width: calc(100% - 50px);
      }

      .close-icon {
        position: absolute;
        top: 0;
        right: 14px;
        color: #fff;
        font-size: 18px;
        cursor: pointer;
        line-height: 40px;

        :hover {
          color: #333;
        }
      }
    }

    main {
        --verify-url-error:'请输入网址';
        --verify-name-error:'请输入名称';
        --verify-src-error:'请上传封面';
      .mian-item {
        align-items: center;
        padding: 12px 15px;
        display: grid;
        grid-template-columns: 38px 1fr;
        grid-column-gap: 4px;
        position: relative;
        &::after{
          position: absolute;
          bottom: -7px;
          left: 70px;
          color: #f00;
          font-size: 12px;
        }
        label {
          width: 30px;
          font-size: 14px;
          font-weight: 500;
          color: #343434;
          margin-right: 6px;
          line-height: 35px;
          height: 35px;
          display: block;
        }

        .input {
          border: 1px solid #dddddd;
          border-radius: 15px;
          line-height: 35px;
          height: 35px;
          width: 100%;
          padding: 0 6px;
          box-sizing: border-box;
          overflow: hidden;
          input {
            width: 100%;
            height: 100%;
            float: left;
            caret-color: var(--system-primary-color);
          }
        }
        
      }
      .url-item-error{
        &::after{
         content: var(--verify-url-error);
        }
      }
      .name-item-error{
        &::after{
         content: var(--verify-name-error);
        }
      }
      .src-item-error{
        &::after{
         content: var(--verify-src-error);
        }
      }
    }

    footer {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 60px;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: end;
      padding: 2px 10px;
      box-sizing: border-box;

      .btn {
        font-size: 13px;
        padding: 6px 15px;
        border-radius: 15px;
        margin: 0 6px;
        cursor: pointer;
        display: flex;
        align-items: center;
        font-weight: 500;

        &:hover {
          filter: brightness(0.95);
        }
      }

      .cancel {
        color: #555555;
        background-color: #eaeaea;
        box-shadow: 1px 1px 5px #c9c9c9;
        border: none;
      }

      .ok {
        color: #fff;
        background-color: var(--system-primary-color);
        box-shadow: 1px 1px 3px var(--system-primary-color);
        border: none;
      }
    }
  }
}

.disable {
  opacity: 0.9;
}
</style>
